package com.caseprocessing.integration;

import com.caseprocessing.ai.AIServiceManager;
import com.caseprocessing.ai.language.SemanticDocumentProcessor;
import com.caseprocessing.ai.vision.VisionDocumentAnalyzer;
import com.caseprocessing.api.SiliconFlowClient;
import com.caseprocessing.enhanced.AIEnhancedComplianceChecker;
import com.caseprocessing.enhanced.AIEnhancedDocumentSplitter;
import com.caseprocessing.enhanced.ComplianceModels.*;
import com.caseprocessing.interface.NaturalLanguageInterface;
import com.caseprocessing.model.CaseDocument;
import com.caseprocessing.model.DocumentSegment;
import com.caseprocessing.service.*;

import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * AI增强系统集成器
 * 统一管理和协调所有AI增强组件
 */
public class AIEnhancedSystemIntegrator {
    
    // 核心组件
    private final SiliconFlowClient siliconFlowClient;
    private final AIServiceManager aiServiceManager;
    private final VisionDocumentAnalyzer visionAnalyzer;
    private final SemanticDocumentProcessor semanticProcessor;
    private final AIEnhancedDocumentSplitter documentSplitter;
    private final AIEnhancedComplianceChecker complianceChecker;
    private final NaturalLanguageInterface nlInterface;
    
    // 传统组件
    private final DocumentSplitter traditionalSplitter;
    private final EnhancedComplianceChecker traditionalComplianceChecker;
    private final LegalCitationValidator citationValidator;
    
    // 系统管理
    private final SystemPerformanceMonitor performanceMonitor;
    private final SystemHealthChecker healthChecker;
    private final ScheduledExecutorService scheduler;
    private final SystemConfiguration config;
    
    public AIEnhancedSystemIntegrator(String siliconFlowApiKey) {
        // 初始化核心组件
        this.siliconFlowClient = new SiliconFlowClient(siliconFlowApiKey);
        this.aiServiceManager = new AIServiceManager(siliconFlowApiKey);
        this.visionAnalyzer = new VisionDocumentAnalyzer(siliconFlowClient);
        this.semanticProcessor = new SemanticDocumentProcessor(siliconFlowClient);
        
        // 初始化传统组件
        this.traditionalSplitter = new DocumentSplitter();
        this.traditionalComplianceChecker = new EnhancedComplianceChecker();
        this.citationValidator = new LegalCitationValidator();
        
        // 初始化AI增强组件
        this.documentSplitter = new AIEnhancedDocumentSplitter(traditionalSplitter, aiServiceManager);
        this.complianceChecker = new AIEnhancedComplianceChecker(
            traditionalComplianceChecker, aiServiceManager, semanticProcessor, visionAnalyzer, citationValidator
        );
        this.nlInterface = new NaturalLanguageInterface(
            aiServiceManager, semanticProcessor, complianceChecker, documentSplitter
        );
        
        // 初始化系统管理
        this.performanceMonitor = new SystemPerformanceMonitor();
        this.healthChecker = new SystemHealthChecker();
        this.scheduler = Executors.newScheduledThreadPool(2);
        this.config = new SystemConfiguration();
        
        // 启动后台任务
        startBackgroundTasks();
    }
    
    /**
     * 使用配置文件中的API密钥创建系统集成器
     */
    public AIEnhancedSystemIntegrator() {
        this(null);
    }
    
    /**
     * 完整的案卷处理流程
     * 集成所有AI增强功能
     */
    public CompletableFuture<CompleteProcessingResult> processCompleteCase(
            CaseDocument caseDocument,
            ProcessingOptions options) {
        
        long startTime = System.currentTimeMillis();
        String processingId = UUID.randomUUID().toString();
        
        performanceMonitor.recordProcessingStart(processingId, caseDocument);
        
        return CompletableFuture.supplyAsync(() -> {
            CompleteProcessingResult result = new CompleteProcessingResult();
            result.setProcessingId(processingId);
            result.setCaseDocument(caseDocument);
            result.setStartTime(LocalDateTime.now());
            
            try {
                // 1. 文档预处理和验证
                PreprocessingResult preprocessing = preprocessDocument(caseDocument, options);
                result.setPreprocessingResult(preprocessing);
                
                if (!preprocessing.isValid()) {
                    result.setSuccess(false);
                    result.setErrorMessage("文档预处理失败: " + preprocessing.getIssues());
                    return result;
                }
                
                // 2. AI增强文档分割
                List<DocumentSegment> segments = executeDocumentSplitting(caseDocument, options).join();
                result.setDocumentSegments(segments);
                
                // 3. AI增强合规检查
                List<AIComplianceResult> complianceResults = executeComplianceChecking(segments, options).join();
                result.setComplianceResults(complianceResults);
                
                // 4. 综合质量评估
                QualityAssessmentResult qualityAssessment = performQualityAssessment(segments, complianceResults, options);
                result.setQualityAssessment(qualityAssessment);
                
                // 5. 生成处理报告
                ProcessingReport report = generateProcessingReport(result, options);
                result.setProcessingReport(report);
                
                result.setSuccess(true);
                result.setEndTime(LocalDateTime.now());
                
                // 记录性能指标
                long processingTime = System.currentTimeMillis() - startTime;
                performanceMonitor.recordProcessingComplete(processingId, processingTime, result);
                
                return result;
                
            } catch (Exception e) {
                result.setSuccess(false);
                result.setErrorMessage("处理过程中发生错误: " + e.getMessage());
                result.setEndTime(LocalDateTime.now());
                
                performanceMonitor.recordProcessingError(processingId, e);
                return result;
            }
        });
    }
    
    /**
     * 批量案卷处理
     * 支持大规模文档的高效处理
     */
    public CompletableFuture<BatchProcessingResult> processBatchCases(
            List<CaseDocument> caseDocuments,
            BatchProcessingOptions batchOptions) {
        
        BatchProcessingResult batchResult = new BatchProcessingResult();
        batchResult.setBatchId(UUID.randomUUID().toString());
        batchResult.setStartTime(LocalDateTime.now());
        batchResult.setTotalDocuments(caseDocuments.size());
        
        // 按批次大小分组
        List<List<CaseDocument>> batches = partitionDocuments(caseDocuments, batchOptions.getBatchSize());
        
        List<CompletableFuture<List<CompleteProcessingResult>>> batchFutures = new ArrayList<>();
        
        for (List<CaseDocument> batch : batches) {
            CompletableFuture<List<CompleteProcessingResult>> batchFuture = 
                processBatchWithRateLimit(batch, batchOptions);
            batchFutures.add(batchFuture);
        }
        
        return CompletableFuture.allOf(batchFutures.toArray(new CompletableFuture[0]))
                .thenApply(v -> {
                    List<CompleteProcessingResult> allResults = batchFutures.stream()
                            .flatMap(future -> future.join().stream())
                            .collect(java.util.stream.Collectors.toList());
                    
                    batchResult.setResults(allResults);
                    batchResult.setEndTime(LocalDateTime.now());
                    batchResult.setSuccessCount((int) allResults.stream().filter(CompleteProcessingResult::isSuccess).count());
                    batchResult.setFailureCount(allResults.size() - batchResult.getSuccessCount());
                    
                    // 生成批量处理统计
                    BatchStatistics statistics = generateBatchStatistics(allResults, batchOptions);
                    batchResult.setStatistics(statistics);
                    
                    return batchResult;
                });
    }
    
    /**
     * 系统健康检查
     * 检查所有组件的运行状态
     */
    public CompletableFuture<SystemHealthReport> performSystemHealthCheck() {
        return CompletableFuture.supplyAsync(() -> {
            SystemHealthReport report = new SystemHealthReport();
            report.setCheckTime(LocalDateTime.now());
            
            // 检查SiliconFlow API连接
            CompletableFuture<Boolean> apiHealth = siliconFlowClient.healthCheck();
            
            // 检查各组件状态
            Map<String, ComponentHealth> componentHealthMap = new HashMap<>();
            
            try {
                // AI服务管理器健康检查
                componentHealthMap.put("AIServiceManager", 
                    checkComponentHealth("AIServiceManager", () -> aiServiceManager.healthCheck().join()));
                
                // 视觉分析器健康检查
                componentHealthMap.put("VisionAnalyzer", 
                    checkComponentHealth("VisionAnalyzer", () -> true)); // 简化检查
                
                // 语义处理器健康检查
                componentHealthMap.put("SemanticProcessor", 
                    checkComponentHealth("SemanticProcessor", () -> true)); // 简化检查
                
                // 自然语言接口健康检查
                componentHealthMap.put("NaturalLanguageInterface", 
                    checkComponentHealth("NaturalLanguageInterface", () -> 
                        nlInterface.getActiveSessionCount() >= 0));
                
                report.setComponentHealth(componentHealthMap);
                
                // 整体健康状态
                boolean overallHealthy = componentHealthMap.values().stream()
                        .allMatch(health -> health.getStatus() == HealthStatus.HEALTHY);
                report.setOverallHealth(overallHealthy ? HealthStatus.HEALTHY : HealthStatus.DEGRADED);
                
                // API连接状态
                report.setApiConnected(apiHealth.join());
                
            } catch (Exception e) {
                report.setOverallHealth(HealthStatus.UNHEALTHY);
                report.setHealthIssues(Arrays.asList("健康检查过程中发生错误: " + e.getMessage()));
            }
            
            return report;
        });
    }
    
    /**
     * 性能优化
     * 动态调整系统参数以优化性能
     */
    public PerformanceOptimizationResult optimizeSystemPerformance() {
        PerformanceOptimizationResult result = new PerformanceOptimizationResult();
        result.setOptimizationTime(LocalDateTime.now());
        
        // 获取性能指标
        PerformanceMetrics currentMetrics = performanceMonitor.getCurrentMetrics();
        
        List<OptimizationAction> actions = new ArrayList<>();
        
        // 基于性能指标进行优化
        if (currentMetrics.getAverageProcessingTime() > config.getMaxAcceptableProcessingTime()) {
            // 处理时间过长，调整并发参数
            actions.add(adjustConcurrencySettings(currentMetrics));
        }
        
        if (currentMetrics.getErrorRate() > config.getMaxAcceptableErrorRate()) {
            // 错误率过高，调整重试参数
            actions.add(adjustRetrySettings(currentMetrics));
        }
        
        if (currentMetrics.getMemoryUsage() > config.getMaxAcceptableMemoryUsage()) {
            // 内存使用过高，调整缓存参数
            actions.add(adjustCacheSettings(currentMetrics));
        }
        
        result.setOptimizationActions(actions);
        result.setExpectedImprovement(calculateExpectedImprovement(actions, currentMetrics));
        
        return result;
    }
    
    /**
     * 自然语言交互入口
     */
    public CompletableFuture<com.caseprocessing.interface.ConversationModels.ConversationResponse> 
    processNaturalLanguageQuery(String sessionId, String userQuery, Map<String, Object> context) {
        return nlInterface.processUserQuery(sessionId, userQuery, context);
    }
    
    // ============ 私有方法 ============
    
    /**
     * 文档预处理
     */
    private PreprocessingResult preprocessDocument(CaseDocument caseDocument, ProcessingOptions options) {
        PreprocessingResult result = new PreprocessingResult();
        List<String> issues = new ArrayList<>();
        
        // 基本验证
        if (caseDocument.getContent() == null || caseDocument.getContent().trim().isEmpty()) {
            issues.add("文档内容为空");
        }
        
        if (caseDocument.getTotalPages() <= 0) {
            issues.add("文档页数无效");
        }
        
        // 质量检查
        if (options.isEnableQualityCheck()) {
            // 简化的质量检查
            if (caseDocument.getContent().length() < 100) {
                issues.add("文档内容过短，可能不完整");
            }
        }
        
        result.setValid(issues.isEmpty());
        result.setIssues(issues);
        
        return result;
    }
    
    /**
     * 执行文档分割
     */
    private CompletableFuture<List<DocumentSegment>> executeDocumentSplitting(
            CaseDocument caseDocument, ProcessingOptions options) {
        
        if (options.isEnableAIEnhancement()) {
            return documentSplitter.splitDocument(caseDocument, caseDocument.getImageUrls());
        } else {
            return CompletableFuture.supplyAsync(() -> traditionalSplitter.splitDocument(caseDocument));
        }
    }
    
    /**
     * 执行合规检查
     */
    private CompletableFuture<List<AIComplianceResult>> executeComplianceChecking(
            List<DocumentSegment> segments, ProcessingOptions options) {
        
        List<CompletableFuture<AIComplianceResult>> futures = new ArrayList<>();
        
        for (DocumentSegment segment : segments) {
            if (options.isEnableAIEnhancement()) {
                CompletableFuture<AIComplianceResult> future = 
                    complianceChecker.comprehensiveComplianceCheck(segment, null, Collections.emptyList());
                futures.add(future);
            } else {
                // 传统合规检查
                CompletableFuture<AIComplianceResult> future = CompletableFuture.supplyAsync(() -> {
                    AIComplianceResult result = new AIComplianceResult();
                    // 简化的传统检查结果转换
                    result.setOverallComplianceScore(0.8);
                    result.setConfidence(0.7);
                    return result;
                });
                futures.add(future);
            }
        }
        
        return CompletableFuture.allOf(futures.toArray(new CompletableFuture[0]))
                .thenApply(v -> futures.stream()
                        .map(CompletableFuture::join)
                        .collect(java.util.stream.Collectors.toList()));
    }
    
    /**
     * 质量评估
     */
    private QualityAssessmentResult performQualityAssessment(
            List<DocumentSegment> segments,
            List<AIComplianceResult> complianceResults,
            ProcessingOptions options) {
        
        QualityAssessmentResult result = new QualityAssessmentResult();
        
        // 分割质量评估
        double avgSplitConfidence = segments.stream()
                .mapToDouble(DocumentSegment::getConfidence)
                .average()
                .orElse(0.0);
        result.setSplittingQualityScore(avgSplitConfidence);
        
        // 合规质量评估
        double avgComplianceScore = complianceResults.stream()
                .mapToDouble(AIComplianceResult::getOverallComplianceScore)
                .average()
                .orElse(0.0);
        result.setComplianceQualityScore(avgComplianceScore);
        
        // 整体质量评估
        double overallScore = (avgSplitConfidence * 0.4 + avgComplianceScore * 0.6);
        result.setOverallQualityScore(overallScore);
        
        // 质量等级
        if (overallScore >= 0.9) {
            result.setQualityLevel("优秀");
        } else if (overallScore >= 0.8) {
            result.setQualityLevel("良好");
        } else if (overallScore >= 0.6) {
            result.setQualityLevel("可接受");
        } else {
            result.setQualityLevel("需要改进");
        }
        
        return result;
    }
    
    /**
     * 生成处理报告
     */
    private ProcessingReport generateProcessingReport(
            CompleteProcessingResult result, ProcessingOptions options) {
        
        ProcessingReport report = new ProcessingReport();
        report.setReportId(UUID.randomUUID().toString());
        report.setGenerationTime(LocalDateTime.now());
        
        // 基本统计
        report.setTotalPages(result.getCaseDocument().getTotalPages());
        report.setSegmentCount(result.getDocumentSegments().size());
        report.setProcessingTimeMs(
            java.time.Duration.between(result.getStartTime(), result.getEndTime()).toMillis()
        );
        
        // 质量统计
        if (result.getQualityAssessment() != null) {
            report.setOverallQuality(result.getQualityAssessment().getQualityLevel());
            report.setQualityScore(result.getQualityAssessment().getOverallQualityScore());
        }
        
        // 合规统计
        if (result.getComplianceResults() != null) {
            long highRiskCount = result.getComplianceResults().stream()
                    .filter(cr -> cr.getRiskLevel() == ComplianceRiskLevel.HIGH)
                    .count();
            report.setHighRiskIssues((int) highRiskCount);
        }
        
        return report;
    }
    
    /**
     * 启动后台任务
     */
    private void startBackgroundTasks() {
        // 定期性能监控
        scheduler.scheduleAtFixedRate(() -> {
            try {
                performanceMonitor.collectMetrics();
            } catch (Exception e) {
                System.err.println("性能监控任务失败: " + e.getMessage());
            }
        }, 1, 5, TimeUnit.MINUTES);
        
        // 定期健康检查
        scheduler.scheduleAtFixedRate(() -> {
            try {
                performSystemHealthCheck();
            } catch (Exception e) {
                System.err.println("健康检查任务失败: " + e.getMessage());
            }
        }, 1, 10, TimeUnit.MINUTES);
        
        // 定期清理会话
        scheduler.scheduleAtFixedRate(() -> {
            try {
                // 清理过期会话的逻辑
            } catch (Exception e) {
                System.err.println("会话清理任务失败: " + e.getMessage());
            }
        }, 30, 30, TimeUnit.MINUTES);
    }
    
    // 其他辅助方法的简化实现...
    private List<List<CaseDocument>> partitionDocuments(List<CaseDocument> documents, int batchSize) {
        List<List<CaseDocument>> batches = new ArrayList<>();
        for (int i = 0; i < documents.size(); i += batchSize) {
            int endIndex = Math.min(i + batchSize, documents.size());
            batches.add(documents.subList(i, endIndex));
        }
        return batches;
    }
    
    private CompletableFuture<List<CompleteProcessingResult>> processBatchWithRateLimit(
            List<CaseDocument> batch, BatchProcessingOptions options) {
        return CompletableFuture.supplyAsync(() -> {
            List<CompleteProcessingResult> results = new ArrayList<>();
            // 简化的批量处理实现
            return results;
        });
    }
    
    private BatchStatistics generateBatchStatistics(
            List<CompleteProcessingResult> results, BatchProcessingOptions options) {
        return new BatchStatistics(); // 简化实现
    }
    
    private ComponentHealth checkComponentHealth(String componentName, java.util.function.Supplier<Boolean> healthCheck) {
        try {
            boolean healthy = healthCheck.get();
            return new ComponentHealth(componentName, 
                healthy ? HealthStatus.HEALTHY : HealthStatus.DEGRADED);
        } catch (Exception e) {
            return new ComponentHealth(componentName, HealthStatus.UNHEALTHY, e.getMessage());
        }
    }
    
    private OptimizationAction adjustConcurrencySettings(PerformanceMetrics metrics) {
        return new OptimizationAction("调整并发设置", "增加并发线程数以提高处理速度");
    }
    
    private OptimizationAction adjustRetrySettings(PerformanceMetrics metrics) {
        return new OptimizationAction("调整重试设置", "优化重试策略以降低错误率");
    }
    
    private OptimizationAction adjustCacheSettings(PerformanceMetrics metrics) {
        return new OptimizationAction("调整缓存设置", "优化缓存策略以降低内存使用");
    }
    
    private double calculateExpectedImprovement(List<OptimizationAction> actions, PerformanceMetrics metrics) {
        return 0.15; // 简化计算，预期15%的性能提升
    }
    
    /**
     * 关闭系统
     */
    public void shutdown() {
        scheduler.shutdown();
        try {
            if (!scheduler.awaitTermination(30, TimeUnit.SECONDS)) {
                scheduler.shutdownNow();
            }
        } catch (InterruptedException e) {
            scheduler.shutdownNow();
            Thread.currentThread().interrupt();
        }
    }
}